# -*- coding: utf-8 -*-


import os

import Tkinter as tk
import tkFileDialog
from ScrolledText import ScrolledText

def add_fs_items(parent, fs_items):
    """
    add to parent a Text field with a list of all fs_items
    """
    itemsfield = ScrolledText(
        parent, width = 79, height = 5
    )
    itemsfield.pack()

    for item in fs_items:
        itemsfield.insert(tk.END, "%r\n" % item)


def meta_key_select(parent, fs_items):
    """
    ToDo: Should be used a base-geretic-listbox-select class
    
    Add a multipe choice list with all existing meta key from all fs_items
    """
    listbox = tk.Listbox(
        parent, selectmode=tk.MULTIPLE,
        height=5, width=79,
        exportselection=tk.FALSE
    )
    listbox.pack()

    added = []
    for fs_item in fs_items:
        for key in fs_item.meta.keys():
            if key not in added:
                added.append(key)
                listbox.insert(tk.END, key)

    return listbox


def askfilepath(title, initialfile, oldpath=None):
    
    def check_path(path):
        if not path or not os.path.isfile(path):
            return False
        
        filename = os.path.split(path)[1]
        if filename == initialfile:
            return True
        else:
            return False
    
    if check_path(oldpath) == True:
        return oldpath

#    name, ext = os.path.splitext(initialfile)
    
    new_path = tkFileDialog.askopenfilename(
        title=title, initialfile=initialfile, 
        filetypes=[(initialfile,initialfile)],
    )
    return askfilepath(title, initialfile, new_path)